<template>
	<!-- 新建物料单 -->
	<HeaderNavTabarVue :title="title">
		<template #right>
			<span v-if="pageStatus === 2 && ItemRequisitionList.underwayOutcome === '跟进中'" @click="finished">完成</span>
		</template>
	</HeaderNavTabarVue>
	<view class="material" :style="'min-height: ' + boxHeight + 'rpx;'">
		<view class="main">
			<!-- 跟进详情 -->
			<!-- 			<view class="main-content-row">
				<view class="picker-content">
					<view class="measurement-info-list">
						<text class="info-list-left isrequired">再次拜访时间</text>
						<view class="info-list-right"                 >
							<view class="info-content">
								{{ ItemRequisitionList.underwayTime }}
							</view>
						</view>
					</view>
				</view>
			</view> -->

			<view class="main-content-row">
				<view class="main-content-row main-content-row-center">
					<MyPicker @getVlaue="getVlaue" @closePop="closePop" ref="customerPickerRef" popupTitle="请选择客户名称">
						<view class="picker-content" @tap="toggle">
							<view class="measurement-info-list">
								<text class="info-list-left isrequired">客户名称</text>
								<view class="info-list-right">
									<view v-if="ItemRequisitionList.customerName"
										:class="pageStatus === 2 || pageStatus === 3 || isAgainVisit ? 'uni-input disabledColor' : 'uni-input' ">
										{{ ItemRequisitionList.customerName }}
									</view>
									<view class="uni-inputs" v-else>请选择</view>
									<i v-if="pageStatus === 1" class="iconfont icon-youjiantou"></i>
								</view>
							</view>
						</view>
					</MyPicker>

					<view class="picker-content">
						<view class="measurement-info-list">
							<text class="info-list-left isrequired">联系电话</text>
							<view class="info-list-right">
								<input :disabled="isAgainVisit || pageStatus === 2 || pageStatus === 3" adjust-position type="number"
									:class="pageStatus === 2 || pageStatus === 3 || isAgainVisit ? 'uni-input placeholder-right disabledColor' : 'uni-input placeholder-right' "
									placeholder="请输入" v-model="ItemRequisitionList.contactPhone" />
							</view>
						</view>
					</view>
					<view class="picker-content">
						<view class="measurement-info-list">
							<text class="info-list-left isrequired">地址</text>
							<view class="info-list-right">
								<input :disabled="pageStatus === 2 || pageStatus === 3 || isAgainVisit" adjust-position type="text"
									:class="pageStatus === 2 || pageStatus === 3 || isAgainVisit ? 'uni-input placeholder-right disabledColor' : 'uni-input placeholder-right' "
									placeholder="请输入" v-model="ItemRequisitionList.address" />
							</view>
						</view>
					</view>
					
					<view class="picker-content">
						<view class="measurement-info-list">
							<text class="info-list-left isrequired">客户跟进阶段</text>
							<view class="info-list-right">
								<input :disabled="pageStatus === 3" adjust-position type="text"
									:class="pageStatus === 3 ? 'uni-input placeholder-right disabledColor' : 'uni-input placeholder-right' "
									placeholder="请输入" v-model="ItemRequisitionList.clientUnderwayStage" />
							</view>
						</view>
					</view>
					<!-- 			<view class="picker-content">
						<view class="measurement-info-list">
							<text class="info-list-left isrequired">拜访方式</text>
							<view class="info-list-right">
								<view class="info-content">
									<input :disabled="pageStatus === 2 || pageStatus === 3" adjust-position type="text"
										:class="pageStatus === 2 || pageStatus === 3 ? 'uni-input placeholder-right disabledColor' : 'uni-input placeholder-right' "
										placeholder="请输入" v-model="ItemRequisitionList.visitWay" />
								</view>
							</view>
						</view>
					</view> -->
					<view class="picker-content" @tap="visitMethodsFn">
						<view class="measurement-info-list">
							<text class="info-list-left isrequired">拜访方式</text>
							<view class="info-list-right">
								<view :class="pageStatus === 3 ? 'uni-input placeholder-right disabledColor' : 'uni-input placeholder-right' " v-if="ItemRequisitionList.visitWay">{{ ItemRequisitionList.visitWay }}
								</view>
								<view class="uni-inputs" v-else>请选择</view>
								<i v-if="!ItemRequisitionList.visitWay" class="iconfont icon-youjiantou"></i>
							</view>
						</view>
					</view>
					<uv-picker ref="visitMethodsRef" :columns="visitMethodsColumns" @confirm="visitMethodsConfirm"></uv-picker>

					<view class="picker-content">
						<view class="measurement-info-list">
							<text class="info-list-left isrequired">跟进时间</text>
							<view class="info-list-right">
								<view class="uni-input disabledColor" v-if="pageStatus === 2 || pageStatus === 3">
									{{ dayjs(ItemRequisitionList.updateTime).format('YYYY-MM-DD HH:mm:ss') }} 
								</view>
								<view class="uni-input disabledColor" v-else>
									{{ dayjs(ItemRequisitionList.underwayTime).format('YYYY-MM-DD HH:mm:ss') }}
								</view>
							</view>
						</view>
					</view>

					<view v-if="pageStatus === 2 || pageStatus === 3" class="picker-content">
						<view class="measurement-info-list">
							<text class="info-list-left isrequired">跟进结果</text>
							<view class="info-list-right">
								<view :class="pageStatus === 2 || pageStatus === 3? 'uni-input disabledColor' : 'uni-input' ">
									{{ ItemRequisitionList.underwayOutcome }}
								</view>
							</view>
						</view>
					</view>

				</view>

			</view>
			<view class="main-content-row" style="margin-top: 40rpx;">
				<!-- 拜访详情 -->
				<view v-if="ItemRequisitionList.underwayOutcome === '已完成' ||  pageStatus === 3" class="uploadImage">
					<view class="materialImage-title">
						<view class="isrequired" style="color: #86909c;font-size: 32rpx;">拜访照片</view>
					</view>
					<view class="materialImage-detail">
						<image @click="previewImg(index)" v-for="(item, index) in fileList" :key="index" :src="item"
							mode="aspectFill"></image>
					</view>
				</view>
				<!-- 拜访附件上传 -->
				<view v-else class="">
					<view v-if="ItemRequisitionList.visitWay === '线下拜访'" class="uploadImage">
						<view class="materialImage-title">
							<view style="color: #86909c;font-size: 32rpx;">拜访照片</view>
							<text>最多上传6张</text>
						</view>
						<view class="materialImage-upload">
							<UploadFile :sourceType="['camera']" :imageList="fileLists" :addWaterMark="true"
								@getSuccessUrl="getSuccessUrl" @onDelete="onDelete" />
						</view>
					</view>
					<view v-if="ItemRequisitionList.visitWay === '线上拜访' || ItemRequisitionList.visitWay === '电话拜访'" class="uploadImage">
						<view class="materialImage-title">
							<view style="color: #86909c;font-size: 32rpx;">请上传证明图片</view>
							<text>最多上传6张</text>
						</view>
						<view class="materialImage-title">
							<view style="color: #86909c;font-size: 28rpx;">(电话截屏/沟通记录等)</view>
						</view>
						<view class="materialImage-upload">
							<UploadFile :imageList="fileLists" @getSuccessUrl="getSuccessUrl" @onDelete="onDelete" />
						</view>
						<!-- <audio v-if="audioUrl" :src="audioUrl" controls></audio> -->
						<!-- <button @click="chooseAudio">选择录音文件</button> -->
					</view>
				</view>

				<view class="textarea-box">
					<text style="color: #86909c;font-size: 32rpx;">备注</text>
					<textarea v-model="ItemRequisitionList.remarks" class="textinfo-list" :disabled="pageStatus === 3"
						:placeholder="pageStatus === 3 ? '暂无备注' : '请输入'"></textarea>
				</view>
			</view>

			<!-- 跟进/完成详情 查看拜访记录 -->
			<view v-if="pageStatus === 2" class="look-box" @click="lookHistory">
				查看拜访记录
			</view>

		</view>
		<!-- 拜访申请 -->
		<view v-if="pageStatus === 1 && ItemRequisitionList.underwayOutcome !== '已完成'" class="floor"
			:style="{zIndex: btnZIndex}" @click="submit(1)">
			<button class="go-material-info">
				确认拜访
			</button>
		</view>

		<!-- 跟进详情 -->
		<view v-if="pageStatus === 2 && ItemRequisitionList.underwayOutcome === '跟进中'" :style="{zIndex: btnZIndex}"
			class="floor2">
			<button class="btn btn1" @click="submit(2)">
				保存
			</button>
			<button class="btn btn2" @click="submit(3)">
				再次拜访
			</button>
		</view>

	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		ref,
		reactive,
		nextTick,
	} from 'vue'
	import store from '@/store'
	import {
		getTitleBarHeight
	} from '@/utils/system.js'
	import UploadFile from '@/components/UploadFile/UploadFile.vue'
	import HeaderNavTabarVue from '@/components/HeaderNavTabar/HeaderNavTabar.vue'
	import MyPicker from '@/components/MyPicker/MyPicker.vue'
	import {
		getDate
	} from '@/utils/getDate.js'
	import {
		getUserProfile
	} from '@/api/system/user.js'
	import {
		getWorkApi
	} from '@/api/customer.js'
	import {
		getVisitAddApi,
		getVisitEditApi
	} from '@/api/visit.js'
	import {
		commonUpload
	} from '@/config.js'
	import {
		getToken
	} from '@/utils/auth.js'
	import config from '@/config.js'
	import dayjs from 'dayjs'

	const customerPickerRef = ref(null) // 这个时候获取了子组件 Comp
	const userId = ref(null)
	const title = ref('客户拜访')
	const audioUrl = ref('');
	// 页面内容高度
	const boxHeight =
		(uni.getSystemInfoSync().windowHeight - getTitleBarHeight()) * 2

	let ItemRequisitionList = ref({
		underwayTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 跟进时间
		customerId: '', // 客户ID
		customerName: '', // 客户名称
		address: '', // 地址
		contactPhone: '', // 电话
		visitWay: '', // 拜访方式
		remarks: '', // 备注
	})

	const lastParams = ref({})

	const fileList = ref([])
	const fileLists = ref([])

	// pageStatus 1 申请拜访 2 跟进状态详情 3 历史记录详情
	const pageStatus = ref(1)
	const isAgainVisit = ref(false) // 是否再次拜访
	const btnZIndex = ref(99) // 底部按钮层级
	const visitMethodsRef = ref(null) // 拜访方式picker

	// 打开模态窗
	const toggle = () => {
		if (pageStatus.value === 1 && !isAgainVisit.value) {
			customerPickerRef.value.toggle('bottom') // 调用子组件的 show 方法
		}
		btnZIndex.value = 0
	}

	const closePop = () => {
		btnZIndex.value = 99
	}

	const escortsFn = () => {
		if (pageStatus.value === 1) {
			uni.navigateTo({
				url: '/components/OptionDeptPerson/index?type=person&isDanXuan=1',
			})
		}
	}

	const visitMethodsColumns = [
		['线下拜访', '线上拜访', '电话拜访']
	]
	const visitMethodsConfirm = (e) => {
		ItemRequisitionList.value.visitWay = e.value[0]
		fileList.value = []
		fileLists.value = []
	}
	const visitMethodsFn = () => {
		if(pageStatus.value !== 3){
			visitMethodsRef.value.open()
		}
	}

	// 客户信息
	let customerList = ref([])
	// 获取客户下拉菜单数据
	const getWorkApiData = async (v = '') => {
		let params = {
			customerName: v,
		}
		let {
			code,
			data
		} = await getWorkApi(params)
		if (code == 200) {
			data.forEach((v) => {
				// 过滤掉 null
				customerList.value.push({
					label: [v.primaryClassification, v.customerName].filter(item => item != null).join('/'),
					value: v.customerId,
				})
			})
			store.commit('setCustomerList', customerList.value)
		}
	}

	// 选择的客户数据
	const getVlaue = (v) => {
		ItemRequisitionList.value.customerId = v.value
		ItemRequisitionList.value.customerName = v.label
		customerPickerRef.value.closePop()
		btnZIndex.value = 99
	}

	// 获取上传的图片
	const getSuccessUrl = (fileName) => {
		fileList.value.push(config.baseUrl + fileName)
		fileLists.value.push({
			url: config.baseUrl + fileName,
			extname: 'jpeg',
			name: config.baseUrl + fileName
		})
	}
	// 删除图片后的数据
	const onDelete = (emit) => {
		fileList.value = emit
		fileLists.value = emit.map((item, index) => {
			return {
				name: item,
				extname: 'jpeg',
				url: item,
			}
		})
	}

	const previewImg = (index) => {
		uni.previewImage({
			urls: fileList.value,
			current: index
		})
	}

	// 选择录音文件
	const chooseAudio = () => {
      // 兼容写法：优先使用 uni.chooseFile，否则降级处理
      if (typeof uni.chooseFile === 'function') {
        uni.chooseFile({
          count: 1,
          success: (res) => {
						console.log(res,'res')
            // this.audioPath = res.tempFiles[0].path;
          }
        });
      } else {
        // 旧版本或 App 端使用原生插件
        // #ifdef APP-PLUS
        const fileChooser = uni.requireNativePlugin('FileChooser');
        fileChooser.open((res) => {
					console.log(res,'res')
          // this.audioPath = res.filePaths[0];
        });
        // #endif
      }
	}

	let reg_tel =
		/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
	//校验
	const jiaoyan = (fn) => {
		let obj = {
			underwayTime: dayjs(ItemRequisitionList.value.underwayTime).format('YYYY-MM-DD hh:mm:ss'), // 跟进时间
			customerId: '', // 客户ID
			customerName: '', // 客户名称
			address: '', // 地址
			contactPhone: '', // 电话
			visitWay: '', // 拜访方式
			// remarks: "", // 备注
		}
		let nameTypeEL = []

		for (let key in obj) {
			if (ItemRequisitionList.value[key] == '') {
				nameTypeEL.push(key)
			}
		}
		 // && fileList.value.length > 0
		if (nameTypeEL.length == 0) {
			if (!reg_tel.test(ItemRequisitionList.value.contactPhone)) {
				uni.showToast({
					title: '手机号码格式错误！',
					icon: 'none',
				})
			} else {
				fn()
			}
		} else {
			uni.showToast({
				title: '请输入完整数据',
				icon: 'error',
			})
		}
	}

	// 确认拜访
	const submit = (type) => {
		// type 1 拜访申请 2 修改拜访 3 再次拜访
		const fn = async () => {
			// 再次拜访 (只有再次提交再,不填写不更改)默认更改当前状态 并新建一个当前客户的拜访
			if (type === 3) {
				lastParams.value = JSON.parse(JSON.stringify(ItemRequisitionList.value))
				// lastParams.value.id = ItemRequisitionList.value.id
				lastParams.value.underwayOutcome = "已完成"

				// 新建一个当前客户的拜访
				isAgainVisit.value = true
				pageStatus.value = 1
				fileList.value = []
				fileLists.value = []
				ItemRequisitionList.value.remarks = ''

			} else {
				let params = {
					customerName: ItemRequisitionList.value.customerName,
					customerId: ItemRequisitionList.value.customerId,
					contactPhone: ItemRequisitionList.value.contactPhone,
					address: ItemRequisitionList.value.address,
					visitWay: ItemRequisitionList.value.visitWay,
					underwayTime: dayjs(ItemRequisitionList.value.underwayTime).format('YYYY-MM-DD hh:mm:ss'),
					underwayPerson: ItemRequisitionList.value.underwayPerson,
					imageUrl: JSON.stringify(fileList.value),
					remarks: ItemRequisitionList.value.remarks,
					underwayOutcome: '跟进中', // 跟进结果
					clientUnderwayStage: ItemRequisitionList.value.clientUnderwayStage,
					// clientUnderwayStage: 0, // 客户跟进阶段 0 阶段未完成 1 阶段全部完成(点完成时修改)
					userId: userId.value,
				}
				let Api
				if (type === 1) {
					// 拜访申请
					Api = getVisitAddApi
				} else if (type === 2) {
					// 修改拜访
					Api = getVisitEditApi
					params.id = ItemRequisitionList.value.id
				}
				let {
					code
				} = await Api(params)
				if (code === 200) {
					if (pageStatus.value === 1 && isAgainVisit.value) {
						// 如果是 再次拜访并提交 修改上次再次拜访的状态为已完成
						await getVisitEditApi(lastParams.value)
					}

					uni.showToast({
						title: '提交成功',
						duration: 1500,
						icon: 'success',
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				}
			}

		}
		jiaoyan(fn)
	}

	// 查看拜访记录
	const lookHistory = () => {
		uni.navigateTo({
			url: '/pages/visit/history?customerId=' + ItemRequisitionList.value.customerId
		})
	}

	// 完成
	const finished = () => {
		uni.showModal({
			content: '您确定当前客户拜访阶段全部完成吗？', //模板中提示的内容
			success: async (res) => {
				if (res.confirm) {
					console.log('点击确定')
					const params = {
						id: ItemRequisitionList.value.id,
						underwayOutcome: "已完成",
						// clientUnderwayStage: 1, // 客户跟进阶段 0 阶段未完成 1 阶段全部完成
					}
					let {
						code
					} = await getVisitEditApi(params)
					if (code === 200) {
						uni.showToast({
							title: '提交成功',
							duration: 1500,
							icon: 'success',
						})

						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					}
				}
			}
		})
	}

	// 保存
	const save = async () => {
		console.log('点击保存')
		console.log(fileList.value, 'fileList')
		// if (fileList.value.length === 0) {
		// 	return uni.showToast({
		// 		title: '请输入完整数据',
		// 		icon: 'error',
		// 	})
		// }

		let {
			code
		} = await getVisitEditApi(params)
		if (code === 200) {
			uni.showToast({
				title: '保存成功',
				duration: 1500,
				icon: 'success',
			})

			setTimeout(() => {
				uni.navigateBack()
			}, 1000)
		}
	}

	// 再次拜访
	const subSubmit = () => {
		console.log('点击再次拜访')
	}

	const getUserProfileFn = async () => {
		let {
			code,
			data
		} = await getUserProfile()
		if (code === 200) {
			userId.value = data.userId
			ItemRequisitionList.value.underwayPerson = data.nickName
		}
	}

	onShow(() => {
		// 监听事件 获取选择的人员
		// uni.$on('getOptionPerson', (data) => {
		// 	ItemRequisitionList.value.escorts = data.map((v) => {
		// 		return {
		// 			userId: v.userId,
		// 			nickName: v.nickName,
		// 		}
		// 	})
		// });
	})

	onLoad((options) => {
		// status 1 申请拜访 2 跟进状态详情 3 历史记录详情
		if (options.status) {
			pageStatus.value = Number(options.status)
		}

		// 回显
		if (options.item) {
			ItemRequisitionList.value = JSON.parse(options.item)
			fileList.value = JSON.parse(ItemRequisitionList.value.imageUrl)
			nextTick(() => {
				JSON.parse(ItemRequisitionList.value.imageUrl).map(item => {
					fileLists.value.push({
						url: item,
						extname: 'jpeg',
						name: item
					})
				})
			})
		}

		if (Number(options.status) === 3) {
			title.value = '拜访详情'
		}
		getWorkApiData()
		getUserProfileFn()
	})
</script>

<style lang="scss" scoped>
	// @import '@dcloudio/uni-components/style/audio.css';
	@import '/static/style/index.scss';

	.disabledColor {
		color: #86909C;
	}

	.uni-inputs {
		color: #86909c !important;
	}

	.textarea-box {
		padding: 20rpx;
		margin-top: 20rpx;

		.info-list-left {
			// @include font-color-auxiliary;
			color: #1d2129;
			font-size: $font-size-base;
		}

		.textinfo-list {
			margin-top: 20rpx;
			width: 100%;
			height: 200rpx;
		}
	}


	.uploadImage {
		// @include background-color;
		background-color: $uni-bg-lin;
		padding: $spacing-row-base $spacing-col-base;
		border-radius: 16rpx;

		.materialImage-title {
			@include flex(center, space-between);
			margin-bottom: $spacing-row-base;

			h4 {
				font-weight: 400;
				// @include font-color;
				color: $uni-fc-lin;
			}

			text {
				// @include font-color-auxiliary;
				color: $uni-fc-fu-lin;
			}
		}

		.materialImage-upload {}

		.materialImage-detail {
			width: 100vw;
			display: flex;
			align-items: center;
			flex-wrap: wrap;

			image {
				width: calc(100% / 3 - 60rpx);
				height: 190rpx;
				margin: 0 20rpx 20rpx 0;
				border-radius: 8rpx;

				:nth-child(3n) {
					margin-right: 0;
				}
			}

		}
	}

	.material {
		position: relative;
		padding: $spacing-row-base;
		box-sizing: border-box;
		// @include main-area-bgColor;
		background-color: $uni-bai;
		overflow-y: auto;
		padding-bottom: 200rpx;

		:deep(.uni-input-input) {
			text-align: right;
		}

		.main {
			.main-content-row-center {
				margin: $spacing-col-base 0;
			}

			.main-content-row {
				// @include background-color;
				background-color: $uni-bg-lin;
				border-radius: 16rpx;

				.measurement-info-list {
					@include flex($align: center, $justify: space-between);
					padding: $spacing-row-base;

					.info-list-left {
						// @include font-color-auxiliary;
						color: $uni-fc-fu-lin;
						font-size: $font-size-base;
					}

					.info-list-right {
						@include flex($align: center);

						.info-content {
							@include textStyleBase;
							font-size: 34rpx;
						}

						.iconfont {
							margin-left: 16rpx;
							// @include font-color-auxiliary;
							color: $uni-fc-fu-lin;
						}
					}

					.unit {
						// @include font-color-auxiliary;
						color: $uni-fc-fu-lin;
					}
				}
			}

			.main-content-bottom {
				margin-top: $spacing-col-base;
			}

			.look-box {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top: 40rpx;
				color: #165DFF;
				font-size: 24rpx;
			}
		}

		.floor {
			width: 100%;
			position: fixed;
			bottom: 0;
			left: 0;
			padding: 32rpx;
			background-color: #fff;
			z-index: 99;

			button {
				display: flex;
				justify-content: center;
				align-items: center;
				@include flex($align: center, $flex-column: column);
				line-height: normal;
				padding: 14rpx 0;
				box-sizing: border-box;
				border-radius: 16rpx;
				background: var(--primary-primary-6, #165DFF);
				color: #fff;
			}
		}

		.floor2 {
			width: 100%;
			position: fixed;
			bottom: 0;
			left: 0;
			padding: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #fff;
			z-index: 999;

			.btn {
				width: 48%;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 16rpx;
			}

			.btn1 {
				background-color: #fff;
				border: 1rpx solid #165DFF;
				color: #165DFF;
			}

			.btn2 {
				background: var(--primary-primary-6, #165DFF);
				color: #fff;
			}
		}
	}
</style>